package controllers

import (
	"amz"
	"github.com/astaxie/beego"
	"io/ioutil"
	"log"
	"net/http"
)

type APIController struct {
	beego.Controller
}

// /asin/{asin}/{market}
func (c *APIController) Asin() {
	defer func() {
		if r := recover(); r != nil {
			log.Println(r)
			c.Abort("503")
		}
	}()

	asin := c.Ctx.Params[":asin"]
	market := c.Ctx.Params[":market"]
	log.Println(asin, market)

	resp, err := http.Get("http://www.amazon.com/dp/" + asin)
	defer resp.Body.Close()
	if err != nil {
		c.Abort("503")
	}

	as := &amz.USAsin{}
	html, _ := ioutil.ReadAll(resp.Body)
	_, err = as.Init(html)
	if err != nil {
		c.Abort("503")
	}

	c.Data["json"] = &amz.Listing{Title: as.Title(), Rating: as.ReviewRating()}
	c.ServeJson()
}
